﻿using System;
using System.IO;

namespace DelegateAppl{
    class PrintString{
        static FileStream fs;
        static StreamWriter sw;
        // 委托声明
        public delegate void printString(string s);

        // 该方法打印到控制台
        public static void WriteToScreen(string str){
            Console.WriteLine("The String is: {0}", str);
        }
        // 该方法打印到文件
        public static void WriteToFile(string s)
        {
            // 使用用户文档目录避免权限问题
            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string filePath = Path.Combine(documentsPath, "message.txt");
    
            // 使用using语句自动管理资源，避免文件占用和资源泄漏[1,6](@ref)
            using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.WriteLine(s);
                // Flush和Close会自动由using语句处理[1](@ref)
            }
    
            Console.WriteLine($"文件已成功写入: {filePath}");
        }
        // 该方法把委托作为参数，并使用它调用方法
        public static void sendString(printString ps){
            ps("Hello World");
        }
        public static void TestMain(){
            printString ps1 = new printString(WriteToScreen);
            printString ps2 = new printString(WriteToFile);
            sendString(ps1);
            sendString(ps2);
            Console.ReadKey();
        }
    }
}